/**
 * Copyright &copy; 2012-2016 <a href="https://www.kaaction.com">KAA</a> All rights reserved.
 */
package com.kaaction.modules.operate.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.kaaction.common.config.Global;
import com.kaaction.common.web.BaseController;
import com.kaaction.common.utils.StringUtils;
import com.kaaction.modules.operate.entity.Activity;
import com.kaaction.modules.operate.entity.ActivityChannel;
import com.kaaction.modules.operate.entity.Channel;
import com.kaaction.modules.operate.service.ActivityChannelService;
import com.kaaction.modules.operate.service.ActivityService;
import com.kaaction.modules.operate.service.ChannelService;

/**
 * 活动Controller
 * @author zengbiao
 * @version 2017-04-12
 */
@Controller
@RequestMapping(value = "${adminPath}/operate/activity")
public class ActivityController extends BaseController {

	@Autowired
	private ActivityService activityService;
	
	@Autowired
	private ChannelService channelService;
	
	@Autowired
	private ActivityChannelService activityChannelService;
	
	@ModelAttribute
	public Activity get(@RequestParam(required=false) String id) {
		Activity entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = activityService.get(id);
		}
		if (entity == null){
			entity = new Activity();
		}
		return entity;
	}
	
	@RequiresPermissions("operate:activity:view")
	@RequestMapping(value = {"list", ""})
	public String list(Activity activity, HttpServletRequest request, HttpServletResponse response, Model model) {
		List<Activity> list = activityService.findList(activity); 
		model.addAttribute("list", list);
		return "modules/operate/activityList";
	}

	@RequiresPermissions("operate:activity:view")
	@RequestMapping(value = "form")
	public String form(Activity activity, Model model) {
		if (activity.getParent()!=null && StringUtils.isNotBlank(activity.getParent().getId())){
			activity.setParent(activityService.get(activity.getParent().getId()));
			// 获取排序号，最末节点排序号+30
			if (StringUtils.isBlank(activity.getId())){
				Activity activityChild = new Activity();
				activityChild.setParent(new Activity(activity.getParent().getId()));
				List<Activity> list = activityService.findList(activity); 
				if (list.size() > 0){
					activity.setSort(list.get(list.size()-1).getSort());
					if (activity.getSort() != null){
						activity.setSort(activity.getSort() + 30);
					}
				}
			} else {
				List<ActivityChannel> activityChannelList = activityChannelService.findListByActivityId(activity.getId());
				String channelIds = "";
				for(ActivityChannel ins : activityChannelList){
					channelIds += ("," + ins.getChannelId());
				}
				activity.setChannelIds(channelIds);	
			}
		}
		if (activity.getSort() == null){
			activity.setSort(30);
		}
		
		//生成树状结构的渠道列表
		model.addAttribute("channelList", channelService.findList(new Channel()));
		

		
		model.addAttribute("activity", activity);
		return "modules/operate/activityForm";
	}

	@RequiresPermissions("operate:activity:edit")
	@RequestMapping(value = "save")
	public String save(Activity activity, Model model, HttpServletRequest request, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, activity)){
			return form(activity, model);
		}
		activityService.save(activity);
		addMessage(redirectAttributes, "保存活动成功");
		
		if(activity != null && !StringUtils.isBlank(activity.getId())){
			//1.delete all related records
			activityChannelService.deleteByActivityId(activity.getId());
			
			String channelIds = activity.getChannelIds();
			//2.add 
			if(!StringUtils.isBlank(channelIds) && channelIds.indexOf(",") != -1){
				String[] channelIdArr = channelIds.split(",");
				for(String channelIdStr : channelIdArr) {
					ActivityChannel activityChannel = new ActivityChannel();
					if(!StringUtils.isBlank(channelIdStr)){
						activityChannel.setActvityId(activity.getId());
						activityChannel.setChannelId(channelIdStr);
						activityChannelService.save(activityChannel);
					}
				}
			}
		}
		
		return "redirect:"+Global.getAdminPath()+"/operate/activity/?repage";
	}
	
	@RequiresPermissions("operate:activity:edit")
	@RequestMapping(value = "delete")
	public String delete(Activity activity, RedirectAttributes redirectAttributes) {
		activityService.delete(activity);
		addMessage(redirectAttributes, "删除活动成功");
		return "redirect:"+Global.getAdminPath()+"/operate/activity/?repage";
	}

	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(@RequestParam(required=false) String extId, HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<Activity> list = activityService.findList(new Activity());
		for (int i=0; i<list.size(); i++){
			Activity e = list.get(i);
			if (StringUtils.isBlank(extId) || (extId!=null && !extId.equals(e.getId()) && e.getParentIds().indexOf(","+extId+",")==-1)){
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				map.put("pId", e.getParentId());
				map.put("name", e.getName());
				mapList.add(map);
			}
		}
		return mapList;
	}
	
}